<#include "../layout/base.ftl">
<#macro header>
<script type="text/javascript">
var vfVoucherItem = '<tr><td width="20%" align="left"><input type="text"  name="digest"  style="width:98%"/></td>' +
        '<td width="20%" align="left">' +
        '<input type="text" ondblclick="showSubjectDialog(this)" style="width:98%"/>' +
        '<input name="code" type="hidden"/>' +
        '</td>' +
        '<td width="10%" align="right"><input name="debit"/></td>' +
        '<td width="10%" align="right"><input name="credit"/></td>' +
        '<td width="20%"><div name="type"></div><input name="customerId" type="hidden"/><input name="supplierId" type="hidden"/>' +
        '<input name="deptId" type="hidden"/><input name="userId" type="hidden"/></td>' +
        '<td width="20%" align="center"><button  onclick="deleteVoucherItem(this)">删除</button></td></tr>';

$(function () {
    var companyList = [
        <#if companyList??&&companyList?size&gt;0>
            {text: "", value: "0"},
            <#list companyList as company>
                {text: "${company[2]!""}", value: "${company[0]!""}"}<#if company_has_next>,</#if>
            </#list>
        </#if>
    ];

    $("#vf_footer").before(vfVoucherItem);

    $("#vf_search_panel").omPanel({
        header: false
    });

    $("#vf_company_name").omCombo({
        width: 100,
        dataSource: companyList,
        listAutoWidth: true,
        filterStrategy: 'anywhere',
        editable: false,
        value: '0',
        onValueChange: function (target, newValue, oldValue, event) {
            $('#vf_vchrtypecode').val('').omCombo('setData', '${base}/basic/find_voucher_type_json?id=' + newValue);
        }
    });

    $("#vf_vchrtypecode").omCombo({
        width: 100,
        value: '0',
        editable: false
    });

    $("#vf_create_time").omCalendar({
        width: 100,
        editable: false
    });

    addNumberField();

    $('#vf_buttonbar').omButtonbar({
        width: '100%',
        btns: [
            {label: "新增分录",
                id: "vf_add_button",
                icons: {left: '${base}/css/default/images/edit_add.png'},
                onClick: function () {
                    $("#vf_footer").before(vfVoucherItem);
                    addNumberField();
                }
            }
        ]
    });

    $("#vf_save_voucher_button").omButton({
        onClick: function () {
            var master = {companyId: $("#vf_company_name").omCombo("value"),
                voucherTypeCodeId: $("#vf_vchrtypecode").omCombo("value"),
                createTime: $("#vf_create_time").val(),
                operatorId: $("#vf_operator_id").val(),
                attachment: $("#vf_attachment").val(),
                remarks: $("#vf_remarks").val()};
            var inputs = $("#vf_table :input").serializeArray();
            var items = "[";
            for (var i = 0; i < inputs.length; i++) {
                if (i % 8 == 0)
                    items += "{";
                items += "\"" + inputs[i].name + "\":\"" + inputs[i].value + "\","
                if (i % 8 == 7)
                    items = items.substring(0, items.length - 1) + "},";
            }
            items = items.substring(0, items.length - 1) + "]";
            var voucher = {voucherMaster: json2String(master), voucherItems: items};
            $.post("${base}/voucher_fill/save_voucher", voucher,
                    function (data, textStatus, jqXHR) {
//                        if (data.responseflag == "1") {
//                            $('span#rp_button_search').omButton("click");
//                        }
//                        var type = data.responseflag == "1" ? "success" : "error";
//                        $.omMessageBox.alert({
//                            type: type,
//                            title: '提示',
//                            content: data.responsemessage
//                        });
                    }, "json");
        }
    });

    $("#vf_subject_tree_dialog").omDialog({
        title: "科目代码",
        autoOpen: false,
        resizable: true,
        modal: true,
        width: 380,
        height: 500,
        buttons: [
            {
                text: "关闭",
                click: function () {
                    $("#vf_subject_tree_dialog").omDialog("close");
                }
            }
        ]
    });

    initAssistAccountingType();
});

function showSubjectDialog(textInput) {
    var companyId = $("#vf_company_name").omCombo('value');
    if (companyId == 0) {
        $.omMessageBox.alert({
            type: 'warning',
            title: '提示',
            content: '请先选择公司!'
        });
        return;
    }
    $("#vf_subject_tree").omTree({
        dataSource: '${base}/basic/subject_tree_json?companyId=' + companyId,
        simpleDataModel: true,
        onSelect: function (nodedata) {
            var ndata = nodedata, text = ndata.text, id = ndata.id;
            ndata = $("#vf_subject_tree").omTree("getParent", ndata);
            if (ndata == null) {
                text = "";
                id = "";
            }
            while (ndata != null && ndata.pid != "") {
                text = ndata.text + "/" + text;
                ndata = $("#vf_subject_tree").omTree("getParent", ndata);
            }
            $(textInput).val(text);
            $(textInput).parent().find(":hidden").val(id);
            var html = "<a href='#' onclick='selectAssistAccountingType(this)'>" + nodedata.type + "</a>";
            $(textInput).parent().parent().find("[name='type']").html(html);
            $("#vf_subject_tree_dialog").omDialog("close");
        },
        onBeforeSelect: function (nodedata) {
            //如果选中的是非叶子叶节点不回填
            if (nodedata.children) {
                return false;
            }
        }
    });
    $("#vf_subject_tree_dialog").omDialog("open");
}


function deleteVoucherItem(button) {
    $(button).parent().parent().remove();
    sum("debit", "vf_sum_debit");
    sum("credit", "vf_sum_credit");
}

function addNumberField() {
    $("[name='debit']").omNumberField({
        onBlur: function (value, event) {
            $(this).val(value || '0');
            sum("debit", "vf_sum_debit");
        }
    });
    $("[name='credit']").omNumberField({
        onBlur: function (value, event) {
            $(this).val(value || '0');
            sum("credit", "vf_sum_credit");
        }
    });
}

function sum(inputName, sumInputId) {
    var inputs = $("[name='" + inputName + "']");
    var sum = 0;
    for (var i = 0; i < inputs.length; i++) {
        sum += parseFloat($(inputs[i]).val() || '0');
    }
    $("#" + sumInputId + "").html(sum);
}

function validateData() {
    var sumDebit = $("#vf_sum_debit").html();
    var sumCredit = $("#vf_sum_credit").html();
    if (Math.abs(parseFloat(sumDebit.value) - parseFloat(sumCredit.value)) >= 0.01) {
        $.omMessageBox.alert({type: 'warning', title: '提示', content: '借方不等于贷方,请进行修改!'});
        return false;
    }
}

function initAssistAccountingType(element) {
    $("#vf_select_dialog").omDialog({
        title: "辅助核算",
        autoOpen: false,
        resizable: true,
        modal: true,
        width: 460,
        onOpen: function (event) {
            createVfDialogForm();
            cleanVfDialogForm();
        },
        buttons: [
            {
                text: "确定",
                click: function () {
                    var customerName = $("#vf_customer_name").val();
                    var customerId = $("#vf_customer_id").val();
                    var supplierName = $("#vf_supplier_name").val();
                    var supplierId = $("#vf_supplier_id").val();
                    var deptName = $("#vf_dept_name").next().val();
                    var deptId = $("#vf_dept_name").val();
                    var userName = $("#vf_user_name").next().val();
                    var userId = $("#vf_user_name").val();
                    var name = new Array();
                    if ($.trim(customerName).length != 0) {
                        name.push(customerName);
                        $(element).parent().parent().find("[name='customerId']").val(customerId);
                    }
                    if ($.trim(supplierName).length != 0) {
                        name.push(supplierName);
                        $(element).parent().parent().find("[name='supplierId']").val(supplierId);
                    }
                    if ($.trim(deptName).length != 0) {
                        name.push(deptName);
                        $(element).parent().parent().find("[name='deptId']").val(deptId);
                    }
                    if ($.trim(userName).length != 0) {
                        name.push(userName);
                        $(element).parent().parent().find("[name='userId']").val(userId);
                    }
                    if (name.length != 0) {
                        var html = "<a href='#' onclick='selectAssistAccountingType(this)'>" + name.join("/") + "</a>";
                        $(element).parent().parent().find("[name='type']").html(html);
                    }
                    $("#vf_select_dialog").omDialog("close");
                }
            },
            {
                text: "取消",
                click: function () {
                    $("#vf_select_dialog").omDialog("close");
                }
            }
        ]
    });
}

function createVfDialogForm() {
    addSuggestion('vf_customer_name', 'vf_customer_id', '${base}/basic/find_customer_json');
    addSuggestion('vf_supplier_name', 'vf_supplier_id', '${base}/basic/find_customer_json');
    $('#vf_dept_name').omCombo({
        dataSource: '${base}/basic/find_dept_json?companyId=' + $("#vf_company_name").omCombo('value'),
        editable: false,
        filterStrategy: 'anywhere',
        onValueChange: function (target, newValue, oldValue, event) {
            $('#vf_user_name').val('').omCombo('setData', '${base}/basic/find_user_json?deptId=' + newValue);
        }
    });
    $('#vf_user_name').omCombo({
        editable: false
    });
}

function cleanVfDialogForm() {
    $("#vf_customer_name").val("");
    $("#vf_customer_id").val("");
    $("#vf_supplier_name").val("");
    $("#vf_supplier_id").val("");
    $("#vf_dept_name").omCombo("value", "");
    $("#vf_user_name").omCombo("value", "");
}

function addSuggestion(textInputId, hiddenId, url) {
    $('#' + textInputId).omSuggestion({
        cacheSize: 0,
        listMaxHeight: 100,
        method: 'POST',
        dataSource: url,
        clientFormatter: function (data, index) {
            return data.name;
        },
        onSelect: function (rowData, text, index, event) {
            $('#' + hiddenId).val(rowData.id);
        }
    });

    $('#' + textInputId).keydown(function (event) {
        var curKey = event.which;
        if (curKey == 8 || curKey == 46) {
            $('#' + hiddenId).val("");
            $('#' + textInputId).val("");
        }
    });
}


function selectAssistAccountingType(element) {
    initAssistAccountingType(element);
    $("#vf_select_dialog").omDialog("open");
}

function json2String(O) {
    //return JSON.stringify(jsonobj);
    var S = [];
    var J = "";
    if (Object.prototype.toString.apply(O) === '[object Array]') {
        for (var i = 0; i < O.length; i++)
            S.push(O2String(O[i]));
        J = '[' + S.join(',') + ']';
    }
    else if (Object.prototype.toString.apply(O) === '[object Date]') {
        J = "new Date(" + O.getTime() + ")";
    }
    else if (Object.prototype.toString.apply(O) === '[object RegExp]' || Object.prototype.toString.apply(O) === '[object Function]') {
        J = O.toString();
    }
    else if (Object.prototype.toString.apply(O) === '[object Object]') {
        for (var i in O) {
            O[i] = typeof (O[i]) == 'string' ? '"' + O[i] + '"' : (typeof (O[i]) === 'object' ? O2String(O[i]) : O[i]);
            S.push(i + ':' + O[i]);
        }
        J = '{' + S.join(',') + '}';
    }

    return J;
}
</script>
</#macro>
<#macro body>
<div id="vf_search_panel" class="search_panel">
    <div>
        <span class="label">公&nbsp;&nbsp;&nbsp;司：</span>
        <input id="vf_company_name"/>
        <span class="label">字&nbsp;&nbsp;&nbsp;号：</span>
        <input id="vf_vchrtypecode"/>
        <span class="label">制单时间：</span>
        <input id="vf_create_time" style="width:80px" value="${systemDate?string("yyyy-MM-dd")!""}"/>
        <span class="label">制单人：</span>
        <input type="text" class="input-text" readonly="true"/>
        <input id="vf_operator_id" type="hidden"/>
        <span class="label">附单据数：</span>
        <input id="vf_attachment" class="input-text"/>
    </div>
</div>
<div id="vf_buttonbar"></div>
<table id="vf_table" width="100%" class="form outtable">
    <thead>
    <tr>
        <th>摘要</th>
        <th>科目</th>
        <th>借方</th>
        <th>贷方</th>
        <th>辅助核算</th>
        <th>操作</th>
    </tr>
    </thead>
    <tbody>
    <tr id="vf_footer">
        <td width="20%" style="padding: 0px">合计</td>
        <td width="20%" align="left"></td>
        <td width="10%" align="right" id="vf_sum_debit">0.0</td>
        <td width="10%" align="right" id="vf_sum_credit">0.0</td>
        <td width="20%"></td>
        <td width="20%" align="center"></td>
    </tr>
    </tbody>
</table>
<table width="100%" height="60px" class="form outtable">
    <tr>
        <th width="10%">备注</th>
        <td><textarea id="vf_remarks" style="width: 100%"></textarea></td>
    </tr>
</table>
<div>
    <button id="vf_save_voucher_button">保存</button>
</div>
<div id="vf_subject_tree_dialog">
    <ul id="vf_subject_tree"></ul>
</div>
<div id="vf_select_dialog">
    <table width="100%" class="form outtable">
        <tr>
            <th>客户核算</th>
            <td><input id="vf_customer_name" style="width: 190px"/><input id="vf_customer_id" type="hidden"/></td>
        </tr>
        <tr>
            <th>供应商核算</th>
            <td><input id="vf_supplier_name" style="width: 190px"/><input id="vf_supplier_id" type="hidden"/></td>
        </tr>
        <tr>
            <th>部门核算</th>
            <td><input id="vf_dept_name" style="width: 172px"/></td>
        </tr>
        <tr>
            <th>个人核算</th>
            <td><input id="vf_user_name" style="width: 172px"/></td>
        </tr>
    </table>
</div>
</#macro>